#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/3/15 11:13
# @Author  : Wang Yuhang
# @File    : __init__.py
# @Func    : app包中的程序工厂函数

from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from flask_login import LoginManager
from flask_pagedown import PageDown

from config import config

bootstrap = Bootstrap()
moment = Moment()
db = SQLAlchemy()
mail = Mail()
pagedown = PageDown()

login_manager = LoginManager()
login_manager.session_protection = 'strong'      # 设置防止用户会话被篡改的安全等级
login_manager.login_view = 'auth.login'          # 设置登录页面的端点


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])  # 指定配置类的名称development/testing/production,默认是development
    config[config_name].init_app(app)            # 初始化扩展

    bootstrap.init_app(app)                      # 初始化扩展
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    from .main import main as main_blueprint    # 导入名称为main的蓝本
    app.register_blueprint(main_blueprint)      # 将蓝本注册到程序

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')  # 使用url_prefix参数，蓝本中定义的所有路由都会加上指定的前缀

    from .api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/v1')  # 设置前缀，无需在蓝本中的每个路由中添加版本号了

    return app

